import asyncio
from fastmcp import FastMCP
from fastmcp import Client
import requests
import json
from typing import Annotated
from datetime import datetime
import os

financial_api_key = os.getenv("FINANCIAL_API_KEY")

mcp = FastMCP("financial.mcp")

@mcp.tool()
def get_stock_price(
  ticker: Annotated[str, "Stock ticker symbol (e.g., 'AAPL' for Apple, 'TSLA' for Tesla)"],
  start_date: Annotated[str, "Start date in yyyy-mm-dd format (e.g., '2023-01-01')"],
  end_date: Annotated[str, "End date in yyyy-mm-dd format (e.g., '2023-12-31'). Must be >= start_date."]
) -> list:  
    """
    Retrieves daily historical stock price data for a given ticker symbol over a specified date range 
    using the Financial Datasets API.

    Input Parameters:
        ticker: The stock ticker symbol (e.g., 'AAPL' for Apple Inc., 'TSLA' for Tesla Inc.).
        start_date: Start date of the query in 'yyyy-mm-dd' format (inclusive).
        end_date: End date of the query in 'yyyy-mm-dd' format (inclusive). Must be on or after start_date.

    Output:
        result: A list of dictionaries, each representing daily price data with the following fields:
                - ticker: Stock symbol
                - open: Opening price
                - close: Closing price
                - high: Highest price during the day
                - low: Lowest price during the day
                - volume: Trading volume
                - time: Timestamp in ISO 8601 format (UTC)
                - time_milliseconds: Unix timestamp in milliseconds
                Returns an error message string (e.g., invalid date, API failure) if something goes wrong.
    """

    # Validate date format
    try:
      datetime.strptime(start_date, "%Y-%m-%d")
      datetime.strptime(end_date, "%Y-%m-%d")
    except ValueError:
      return f"❌ Invalid date format. Use yyyy-mm-dd for both start_date and end_date."
    
    headers = {}
    if financial_api_key:
      headers["X-API-KEY"] = financial_api_key
    url = f"https://api.financialdatasets.ai/prices/?ticker={ticker}&interval=day&interval_multiplier=1&start_date={start_date}&end_date={end_date}"
    try:
        response = requests.get(url, headers=headers, timeout=15)
    except requests.RequestException as e:
        return f"❌ Request failed: {e}"

    if response.status_code != 200:
        return f"❌ Error fetching data: {ticker} - {response.status_code} - {response.text}"
    try:
        data = response.json()
    except ValueError:
        return f"❌ Failed to parse JSON response for {ticker}."

    raw_prices = data.get("prices", [])
    if not raw_prices:
        return json.dumps({"error": f"No price data found for {ticker} between {start_date} and {end_date}."})

    return raw_prices

async def main():
    """
    Main entry point for the FastMCP client to interact with the Google News API tool.
    Initializes the client, lists available tools, and calls the news data tool with sample parameters.
    """
    client = Client(mcp)
    async with client:
        # List available tools for debugging/verification
        tools = await client.list_tools()
        print('Available tools:', tools)

        # Call the news data tool with sample parameters
        result = await client.call_tool('get_stock_price', {
            "ticker": "AAPL",
            "start_date": "2023-01-01",
            "end_date": "2023-01-05"
        })
        print('News Data Result:', result)

# Recommended entry point for running the async program
if __name__ == '__main__':
    asyncio.run(main())
